from fastapi import APIRouter, Depends, Query, Request
from sqlalchemy.orm import Session

from app.bigdata.handlers.impala_handler import get_impala_queries_duration_millis_top, get_impala_queries_memory_aggregate, \
    get_impala_queries_memory_estimated
from app.bigdata.handlers.yarn_handler import get_yarn_job_duration_top, get_yarn_job_cpu_top
from app.bigdata.handlers.kudu_handler import KuduInfo, latest_kudu_table_data, kudu_capacity_report_handler, \
    kudu_capacity_table_report_handler
from app.bigdata.handlers.hive_handler import latest_hive_db_data, latest_dbs_table_data, latest_db_table_data, \
    hive_capacity_report_handler, hive_capacity_table_report_handler
from app.bigdata.models.impala_query_info import ImpalaQueryInfo
from app.bigdata.schemas import DateRange
from common.database import get_db
from core.logger import logger
from core.response import resp_200, resp_400
from core.templates import templates
from setting.config import config

router = APIRouter()


@router.get("/kudu/real/table/info", summary="获取kudu集群实时表信息", description="大数据-kudu")
async def get_kudu_table_info_real():
    kudu_info = KuduInfo()
    result = kudu_info.get_tables_info()
    if not result:
        message = "get kudu cluster real time table info failed"
        logger.error(message)
        return resp_400(message)
    return resp_200(result)


@router.get("/kudu/historical/table/info", summary="获取kudu集群历史表信息", description="大数据-kudu")
async def get_kudu_table_info_historical(page: int = Query(1, ge=1), per_page: int = Query(10, ge=0), db: Session = Depends(get_db)):
    result = latest_kudu_table_data(page, per_page, db)
    if not result:
        message = "get kudu cluster historical time table info failed"
        logger.error(message)
        return resp_400(message)
    return resp_200(result)


@router.get("/hive/historical/database/info", summary="获取hive集群历史库信息", description="大数据-hive")
async def get_hive_database_info_historical(start_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="开始日期 YYYY-MM-DD"),
                                            end_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="结束日期 YYYY-MM-DD"),
                                            db: Session = Depends(get_db)):
    result = latest_hive_db_data(start_date, end_date, db)
    if not result:
        message = "get hive cluster historical time database info failed"
        logger.error(message)
        return resp_400(message)
    return resp_200(result)


@router.get("/hive/historical/dbs/table/info", summary="获取hive集群历史表信息", description="大数据-hive")
async def get_hive_dbs_table_info_historical(start_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="开始日期 YYYY-MM-DD"),
                                             end_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="结束日期 YYYY-MM-DD"),
                                             db: Session = Depends(get_db)):
    result = latest_dbs_table_data(start_date, end_date, db)
    if not result:
        message = "get hive cluster historical time databases table info failed"
        logger.error(message)
        return resp_400(message)
    return resp_200(result)


@router.get("/hive/historical/db/table/info", summary="获取hive集群历史表信息", description="大数据-hive")
async def get_hive_db_table_info_historical(database_name: str = Query(..., description="数据库名"),
                                            start_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="开始日期 YYYY-MM-DD"),
                                            end_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="结束日期 YYYY-MM-DD"),
                                            db: Session = Depends(get_db)):
    result = latest_db_table_data(database_name, start_date, end_date, db)
    if not result:
        message = "get hive cluster historical time database table info failed"
        logger.error(message)
        return resp_400(message)
    return resp_200(result)


@router.get('/capacity/kudu/table/report', summary="获取大数据kudu表容量报告", description="大数据")
def get_bigdata_capacity_kudu_table_report(request: Request,
                                           start_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="开始日期 YYYY-MM-DD"),
                                           end_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="结束日期 YYYY-MM-DD"),
                                           db: Session = Depends(get_db)):
    kudu_column, kudu_content = kudu_capacity_table_report_handler(start_date, end_date, db)
    if not kudu_content:
        message = "get kudu table bigdata capacity report info failed"
        logger.error(message)
        return resp_400(message)
    return templates.TemplateResponse("bigdata/kudu_table_capacity.html",
                                      {"request": request, "kudu_tables_column": kudu_column, "kudu_tables_content": kudu_content})


@router.get('/capacity/hive/table/report', summary="获取大数据hive表容量报告", description="大数据")
def get_bigdata_capacity_hive_table_report(request: Request,
                                           start_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="开始日期 YYYY-MM-DD"),
                                           end_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="结束日期 YYYY-MM-DD"),
                                           db: Session = Depends(get_db)):
    hive_column, hive_content = hive_capacity_table_report_handler(start_date, end_date, db)
    if not hive_content:
        message = "get hive table bigdata capacity report info failed"
        logger.error(message)
        return resp_400(message)
    return templates.TemplateResponse("bigdata/hive_table_capacity.html",
                                      {"request": request, "hive_tables_column": hive_column, "hive_tables_content": hive_content})


@router.get('/capacity/report', summary="获取大数据容量报告", description="大数据")
def get_bigdata_capacity_report(request: Request,
                                start_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="开始日期 YYYY-MM-DD"),
                                end_date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="结束日期 YYYY-MM-DD"),
                                db: Session = Depends(get_db)):
    hive_column, hive_content = hive_capacity_report_handler(start_date, end_date, db)
    kudu_column, kudu_content = kudu_capacity_report_handler(start_date, end_date, db)
    if not hive_content:
        message = "get hive bigdata capacity report info failed"
        logger.error(message)
        return resp_400(message)
    if not kudu_content:
        message = "get kudu bigdata capacity report info failed"
        logger.error(message)
        return resp_400(message)
    return templates.TemplateResponse("bigdata/database_capacity.html",
                                      {"request": request, "hive_databases_column": hive_column, "hive_databases_content": hive_content,
                                       "kudu_databases_column": kudu_column, "kudu_databases_content": kudu_content,
                                       "ops_http_url": config.OPS_HTTP_URL, "start_date": start_date, "end_date": end_date})


@router.get("/impala/duration/report", summary="获取impala query 资源消耗TOP10信息", description="大数据-impala")
def get_bigdata_impala_sql_top_report(request: Request,
                                      date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="开始日期 YYYY-MM-DD"),
                                      top: int = 10, db: Session = Depends(get_db)):
    duration_column, duration_content = get_impala_queries_duration_millis_top(date, db, top)
    aggregate_column, aggregate_content = get_impala_queries_memory_aggregate(date, db, top)
    estimated_column, estimated_content = get_impala_queries_memory_estimated(date, db, top)
    return templates.TemplateResponse("bigdata/impala_query.html",
                                      {"request": request, "duration_column": duration_column, "duration_content": duration_content,
                                       "aggregate_column": aggregate_column, "aggregate_content": aggregate_content,
                                       "estimated_column": estimated_column, "estimated_content": estimated_content})


@router.get("/impala/sql", summary="获取impala query 语句信息", description="大数据-impala")
def get_bigdata_impala_sql_report(request: Request,
                                  query_id: str = Query(..., regex=r'([0-9]|[a-z]){16}\:([0-9]|[a-z]){16}', description="impala query id"),
                                  db: Session = Depends(get_db)):
    data = ImpalaQueryInfo.get_response_by_query_id(db, query_id)
    if not data:
        message = f"get impala sql by query_id => {query_id}"
        logger.error(message)
        return resp_400(message)
    return templates.TemplateResponse("bigdata/impala_statement.html",
                                      {"request": request, "query_id": query_id, "statement": data.get("statement")})


@router.get("/yarn/job/report", summary="获取yarn job 资源消耗TOP10信息", description="大数据-yarn")
def get_bigdata_yarn_job_report(request: Request,
                                date: str = Query(None, regex=r'^\d{4}-\d{2}-\d{2}', description="开始日期 YYYY-MM-DD"),
                                top: int = 10, db: Session = Depends(get_db)):
    duration_column, duration_content = get_yarn_job_duration_top(date, db, top)
    cpu_column, cpu_content = get_yarn_job_cpu_top(date, db, top)
    return templates.TemplateResponse("bigdata/yarn_job.html",
                                      {"request": request, "duration_column": duration_column, "duration_content": duration_content,
                                       "cpu_column": cpu_column, "cpu_content": cpu_content})
